package com.gc.server.controller.api;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.gc.server.entity.*;
import com.gc.server.enums.LevelEnum;
import com.gc.server.enums.TodoStatusEnum;
import com.gc.server.enums.TodoTypeEnum;
import com.gc.server.service.*;
import com.gc.server.vo.*;
import com.yf.annotation.IgnoreAuth;
import com.yf.annotation.LoginUserId;
import com.yf.response.R;
import com.yf.response.RRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/todo")
public class ApiToDoController {

    @Autowired
    private TodoService todoService;

    @Autowired
    private GoodsRecordService goodsRecordService;

    @Autowired
    private ActRecordService actRecordService;

    /**
     * 获取计划的所有日程
     *
     * @param userId
     * @param planId
     * @return
     */
    @GetMapping("/plan/{planId}")
    public R list(@LoginUserId Long userId, @PathVariable Long planId) {
        List<TodoEntity> todoEntities = todoService.findByPlanId(planId);
        return R.ok(todoEntities);
    }

    /**
     * 根据时间搜索
     *
     * @param userId
     * @param startDate
     * @param endDate
     * @return
     */
    @GetMapping("/date")
    public R listByDate(@LoginUserId Long userId, Date startDate, Date endDate) {
        List<TodoEntity> todoEntities = todoService.findByDateAndUserId(userId, startDate, endDate);
        return R.ok(todoEntities);
    }

    /**
     * 查找下级
     * @param topUserId
     * @param startDate
     * @param endDate
     * @param userId
     * @return
     */
    @GetMapping("/date/top/user")
    public R listByTopAndUserAndDate(@LoginUserId Long topUserId, Date startDate, Date endDate,Long userId){
        List<TodoEntity> todoEntities = todoService.findByDateAndUserIdAndTopUserId(userId, startDate, endDate,topUserId);
        return R.ok(todoEntities);
    }


    /**
     * 统计
     * @param userId
     * @param startDate
     * @param endDate
     * @return
     */
    @GetMapping("/date/top/sum")
    public R sumByDate(@LoginUserId Long userId,Date startDate, Date endDate){
      List<ToDoSumVo> toDoSumVos =   todoService.sumByDate(userId,startDate ,endDate);
      return R.ok(toDoSumVos);
    }

    @PostMapping("/del")
    public R del(@LoginUserId Long userId, Date date, Integer type) {
        todoService.del(userId, date, type);
        return R.ok();
    }

    /**
     * 获取某人下面人的所有日程
     *
     * @param uid
     * @param userId
     * @param date
     * @return
     */
    @GetMapping("/top")
    public R list(@LoginUserId Long uid, Long userId, Date date) {
        List<TodoEntity> todoEntities = todoService.findMyShopUserUser(uid, userId, date);
        todoEntities = todoEntities.stream().filter(todoEntity -> {
            return !todoEntity.getStatus().equals(TodoStatusEnum.TODO.getIndex());
        }).collect(Collectors.toList());
        return R.ok(todoEntities);
    }


    /**
     * 获取某人下面人的所有日程
     * 分类map
     *
     * @param uid
     * @param userId
     * @param date
     * @return
     */
    @GetMapping("/top/map")
    public R listByTopMap(@LoginUserId Long uid, Date date) {
        List<TodoVo> todoVos = todoService.findVoByTopUser(uid, date);
        Map<Long, List<TodoVo>> map = new HashMap();
        todoVos.forEach(todoVo -> {
            Long key = todoVo.getUser().getId();
            List<TodoVo> vos = new ArrayList<>();
            if (map.containsKey(key)) {
                vos = map.get(key);
            }
            vos.add(todoVo);
            map.put(key, vos);
        });
        return R.ok(map);
    }


    /**
     * 添加日程
     *
     * @param userId
     * @return
     */
    @PostMapping("/add")
    public R add(@LoginUserId Long userId, Integer type, Date date, Long planId, String[] titles) {
        todoService.add(planId, date, type, userId, titles);
        return R.ok();
    }

    /**
     * 删除日程
     *
     * @param userId
     * @param id
     * @return
     */
    @PostMapping("/del/{id}")
    public R del(@LoginUserId Long userId, @PathVariable Long id) {
        todoService.del(userId, id);
        return R.ok();
    }

    @Autowired
    private UserService userService;

    /**
     * 获取单个日程
     *
     * @param userId
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R get(@LoginUserId Long userId, @PathVariable Long id) {
        TodoEntity todoEntity = todoService.get(id);
        List<GoodsRecordEntity> goodsRecordEntities = goodsRecordService.findByToDoId(id);
        List<ActRecordEntity> actRecordEntities = actRecordService.findByToDo(id);
        if(todoEntity.getType().equals(TodoTypeEnum.SEND.getIndex())){
            //查询新增人数
            List<UserEntity> userEntities = userService.findByPidAndDate(todoEntity.getUserId(), todoEntity.getDate());
            todoEntity.setUserNum(userEntities.size());
        }
        return R.ok(todoEntity).putExtra("records", goodsRecordEntities).putExtra("acts", actRecordEntities);
    }

    /**
     * 药店拜访 保存 完成
     *
     * @param userId
     * @param todoId
     * @param type
     * @param todoEntity
     * @param ids
     * @param nums
     * @return
     */
    @PostMapping("/visit/save")
    public R visitSave(@LoginUserId Long userId, TodoEntity todoEntity, Long[] ids, Integer[] nums) {
        TodoEntity res = todoService.completeVisit(todoEntity, userId, ids, nums);
        return R.ok(res);
    }

    /**
     * 完成试用装发放
     *
     * @param userId
     * @param todoEntity
     * @return
     */
    @PostMapping("/send/save")
    public R sendSave(@LoginUserId Long userId, TodoEntity todoEntity) {
        todoService.completeSend(todoEntity, userId);
        return R.ok();
    }
    @PostMapping("/hunt/save")
    public R huntSave(@LoginUserId Long userId, TodoEntity todoEntity){
        todoService.completeHunt(todoEntity, userId);
        return R.ok();
    }

    @PostMapping("/other/save")
    public R otherSave(@LoginUserId Long userId, TodoEntity todoEntity){
        todoService.completeOther(todoEntity, userId);
        return R.ok();
    }

    /**
     * 每次活动场景打卡
     *
     * @return
     */
    @PostMapping("/act/save")
    public R actSave(@LoginUserId Long userId, Long todoId, ActRecordEntity actRecordEntity) {
        if (actRecordEntity.getId() == null) {
            actRecordEntity.setTodoId(todoId);
            actRecordEntity.setDoneTime(new Date());
            actRecordService.save(actRecordEntity);
        }
        return R.ok(actRecordEntity);
    }

    /**
     * 完成活动后总结打卡
     *
     * @return
     */
    @PostMapping("/act/sum/save")
    public R actSave(@LoginUserId Long userId, TodoEntity todoEntity, Long[] ids, Integer[] nums) {
        todoService.completeAct(todoEntity, userId, ids, nums);
        return R.ok();
    }

    @Autowired
    private LevelService levelService;

    //获取计划类型
    @GetMapping("/type")
    public R type(@LoginUserId Long userId) {
        LevelEntity levelEntity = levelService.findByUserId(userId);
        List<ToDoTypeVo> toDoTypeVos = new ArrayList<>();
        if (levelEntity.getLv().equals(LevelEnum.BUS.getIndex())) { //终端代表
            ToDoTypeVo toDoTypeVo1 = new ToDoTypeVo(TodoTypeEnum.VISIT.getValue(), TodoTypeEnum.VISIT.getIndex());
            ToDoTypeVo toDoTypeVo2 = new ToDoTypeVo(TodoTypeEnum.SEND.getValue(), TodoTypeEnum.SEND.getIndex());
            ToDoTypeVo toDoTypeVo3 = new ToDoTypeVo(TodoTypeEnum.ACT.getValue(), TodoTypeEnum.ACT.getIndex());
            ToDoTypeVo toDoTypeVo4 = new ToDoTypeVo(TodoTypeEnum.OTHER.getValue(), TodoTypeEnum.OTHER.getIndex());
            toDoTypeVos.add(toDoTypeVo1);
            toDoTypeVos.add(toDoTypeVo2);
            toDoTypeVos.add(toDoTypeVo3);
            toDoTypeVos.add(toDoTypeVo4);
        } else if (levelEntity.getLv().equals(LevelEnum.MANAGER.getIndex())) {//终端主管
            ToDoTypeVo toDoTypeVo1 = new ToDoTypeVo(TodoTypeEnum.VISIT.getValue(), TodoTypeEnum.VISIT.getIndex());
            ToDoTypeVo toDoTypeVo2 = new ToDoTypeVo(TodoTypeEnum.VISIT_HELP.getValue(), TodoTypeEnum.VISIT_HELP.getIndex());
            ToDoTypeVo toDoTypeVo3 = new ToDoTypeVo(TodoTypeEnum.SEND_HELP.getValue(), TodoTypeEnum.SEND_HELP.getIndex());
            ToDoTypeVo toDoTypeVo4 = new ToDoTypeVo(TodoTypeEnum.ACT_HELP.getValue(), TodoTypeEnum.ACT_HELP.getIndex());
            ToDoTypeVo toDoTypeVo5 = new ToDoTypeVo(TodoTypeEnum.HEAD.getValue(), TodoTypeEnum.HEAD.getIndex());
            ToDoTypeVo toDoTypeVo6 = new ToDoTypeVo(TodoTypeEnum.OTHER.getValue(), TodoTypeEnum.OTHER.getIndex());
            toDoTypeVos.add(toDoTypeVo1);
            toDoTypeVos.add(toDoTypeVo2);
            toDoTypeVos.add(toDoTypeVo3);
            toDoTypeVos.add(toDoTypeVo4);
            toDoTypeVos.add(toDoTypeVo5);
            toDoTypeVos.add(toDoTypeVo6);
        }else if(levelEntity.getLv().equals(LevelEnum.MANAGER1.getIndex())){ // 区域经理
            ToDoTypeVo toDoTypeVo1 = new ToDoTypeVo(TodoTypeEnum.LINK.getValue(), TodoTypeEnum.LINK.getIndex());
            ToDoTypeVo toDoTypeVo2 = new ToDoTypeVo(TodoTypeEnum.HEAD.getValue(), TodoTypeEnum.HEAD.getIndex());
            ToDoTypeVo toDoTypeVo3 = new ToDoTypeVo(TodoTypeEnum.HUNT.getValue(), TodoTypeEnum.HUNT.getIndex());
            ToDoTypeVo toDoTypeVo4 = new ToDoTypeVo(TodoTypeEnum.OTHER.getValue(), TodoTypeEnum.OTHER.getIndex());
            toDoTypeVos.add(toDoTypeVo1);
            toDoTypeVos.add(toDoTypeVo2);
            toDoTypeVos.add(toDoTypeVo3);
            toDoTypeVos.add(toDoTypeVo4);
        }else if(levelEntity.getLv().equals(LevelEnum.MANAGER2.getIndex())){
            ToDoTypeVo toDoTypeVo2 = new ToDoTypeVo(TodoTypeEnum.HEAD.getValue(), TodoTypeEnum.HEAD.getIndex());
            ToDoTypeVo toDoTypeVo3 = new ToDoTypeVo(TodoTypeEnum.HUNT.getValue(), TodoTypeEnum.HUNT.getIndex());
            ToDoTypeVo toDoTypeVo4 = new ToDoTypeVo(TodoTypeEnum.OTHER.getValue(), TodoTypeEnum.OTHER.getIndex());
            toDoTypeVos.add(toDoTypeVo2);
            toDoTypeVos.add(toDoTypeVo3);
            toDoTypeVos.add(toDoTypeVo4);
        }
        return R.ok(toDoTypeVos);
    }


    //获取考核类型
    @GetMapping("/type/score")
    public R scoreType(@LoginUserId Long userId) {
        LevelEntity levelEntity = levelService.findByUserId(userId);
        List<ToDoTypeVo> toDoTypeVos = new ArrayList<>();
        if (levelEntity.getLv().equals(LevelEnum.MANAGER.getIndex())) {//终端主管
            ToDoTypeVo toDoTypeVo1 = new ToDoTypeVo(TodoTypeEnum.VISIT.getValue(), TodoTypeEnum.VISIT.getIndex());
            ToDoTypeVo toDoTypeVo2 = new ToDoTypeVo(TodoTypeEnum.SEND.getValue(), TodoTypeEnum.SEND.getIndex());
            ToDoTypeVo toDoTypeVo3 = new ToDoTypeVo(TodoTypeEnum.ACT.getValue(), TodoTypeEnum.ACT.getIndex());
            ToDoTypeVo toDoTypeVo4 = new ToDoTypeVo(TodoTypeEnum.OTHER.getValue(), TodoTypeEnum.OTHER.getIndex());
            toDoTypeVos.add(toDoTypeVo1);
            toDoTypeVos.add(toDoTypeVo2);
            toDoTypeVos.add(toDoTypeVo3);
            toDoTypeVos.add(toDoTypeVo4);
        }else if(levelEntity.getLv().equals(LevelEnum.MANAGER1.getIndex())){//区域经理
            ToDoTypeVo toDoTypeVo1 = new ToDoTypeVo(TodoTypeEnum.VISIT.getValue(), TodoTypeEnum.VISIT.getIndex());
            ToDoTypeVo toDoTypeVo2 = new ToDoTypeVo(TodoTypeEnum.VISIT_HELP.getValue(), TodoTypeEnum.VISIT_HELP.getIndex());
            ToDoTypeVo toDoTypeVo3 = new ToDoTypeVo(TodoTypeEnum.SEND_HELP.getValue(), TodoTypeEnum.SEND_HELP.getIndex());
            ToDoTypeVo toDoTypeVo4 = new ToDoTypeVo(TodoTypeEnum.ACT_HELP.getValue(), TodoTypeEnum.ACT_HELP.getIndex());
            ToDoTypeVo toDoTypeVo5 = new ToDoTypeVo(TodoTypeEnum.HEAD.getValue(), TodoTypeEnum.HEAD.getIndex());
            ToDoTypeVo toDoTypeVo6 = new ToDoTypeVo(TodoTypeEnum.OTHER.getValue(), TodoTypeEnum.OTHER.getIndex());
            toDoTypeVos.add(toDoTypeVo1);
            toDoTypeVos.add(toDoTypeVo2);
            toDoTypeVos.add(toDoTypeVo3);
            toDoTypeVos.add(toDoTypeVo4);
            toDoTypeVos.add(toDoTypeVo5);
            toDoTypeVos.add(toDoTypeVo6);
        }else if (levelEntity.getLv().equals(LevelEnum.MANAGER2.getIndex())){
            ToDoTypeVo toDoTypeVo1 = new ToDoTypeVo(TodoTypeEnum.LINK.getValue(), TodoTypeEnum.LINK.getIndex());
            ToDoTypeVo toDoTypeVo2 = new ToDoTypeVo(TodoTypeEnum.HEAD.getValue(), TodoTypeEnum.HEAD.getIndex());
            ToDoTypeVo toDoTypeVo3 = new ToDoTypeVo(TodoTypeEnum.HUNT.getValue(), TodoTypeEnum.HUNT.getIndex());
            ToDoTypeVo toDoTypeVo4 = new ToDoTypeVo(TodoTypeEnum.OTHER.getValue(), TodoTypeEnum.HUNT.getIndex());
            toDoTypeVos.add(toDoTypeVo1);
            toDoTypeVos.add(toDoTypeVo2);
            toDoTypeVos.add(toDoTypeVo3);
            toDoTypeVos.add(toDoTypeVo4);
        }
        return R.ok(toDoTypeVos);
    }

    @Autowired
    private RouteService routeService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private SchoolService schoolService;

    //获取增加日程的title列表
    @GetMapping("/title/vo")
    public R vo(@LoginUserId Long userId,Integer type,Date date) {
        List<ToDoTitleVo> vos = new ArrayList<>();
        //药店拜访 药店活动
        if(type==TodoTypeEnum.VISIT.getIndex()||type ==TodoTypeEnum.ACT.getIndex()){
            List<RouteEntity> list = routeService.findByUserId(userId);
            list.forEach(l->{
                List<ShopEntity> shopEntities = shopService.findByRouteId(l.getId());
                ToDoTitleVo vo = new ToDoTitleVo(l.getName(),shopEntities.stream().map(shopEntity -> shopEntity.getShopName()+(shopEntity.getLevel()==null?"":shopEntity.getLevel())).collect(Collectors.toList()));
                vos.add(vo);
            });
        }else if (type==TodoTypeEnum.SEND.getIndex()){ //试用装发放
            List<RouteEntity> list = routeService.findByUserId(userId);
            list.forEach(l->{
                List<SchoolEntity> schoolEntities = schoolService.findByRouteId(l.getId());
                ToDoTitleVo vo = new ToDoTitleVo(l.getName(),schoolEntities.stream().map(shopEntity -> shopEntity.getName()).collect(Collectors.toList()));
                vos.add(vo);
            });
        }else if(type==TodoTypeEnum.VISIT_HELP.getIndex()||type==TodoTypeEnum.SEND_HELP.getIndex()||type==TodoTypeEnum.ACT_HELP.getIndex()){ //药店拜访帮带
            List<TodoVo> todoVos = todoService.findVoByTopUser(userId,date);
            todoVos =  todoVos.stream().filter(todoVo -> todoVo.getTodo().getType().equals(type-3)).collect(Collectors.toList());
            //汇总
            Map<String,List<String>> map = new HashMap<>();
            todoVos.forEach(todoVo -> {
                String name = todoVo.getUser().getCode()+" "+ todoVo.getUser().getName();
                List<String> list = new ArrayList<>();
                if(map.containsKey(name)){
                    list = map.get(name);
                }
                list.add(todoVo.getTodo().getTitle());
                map.put(name,list);
            });
            map.forEach((k,v)->{
                ToDoTitleVo vo = new ToDoTitleVo(k,v);
                vos.add(vo);
            });
        }else if(type ==TodoTypeEnum.HEAD.getIndex()||type == TodoTypeEnum.LINK.getIndex()){//连锁开发或者总部拜访
            List<LinkHeadEntity> headEntities = headService.findByUserId(userId);
            ToDoTitleVo vo = new ToDoTitleVo("连锁总部简称", headEntities.stream().map(LinkHeadEntity::getName).collect(Collectors.toList()));
            vos.add(vo);
        }
        return R.ok(vos);
    }

    @Autowired
    private LinkHeadService headService;

//    @InitBinder
//    public void initDateFormate(WebDataBinder dataBinder) {
//        dataBinder.addCustomFormatter(new DateFormatter("MM/dd/yyyy"));
//        dataBinder.addCustomFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));
//    }


}
